$(function(){
	
	checkALL();
	checkedForm();
	
	$(document).on('change','select.itembank-select',function(){
		var value = parseInt($(this).val());
		var params = {
				url: '/admin/enterprise/exams/questions/'+value,
				type: 'GET',
				dataType: 'json',
				data:{},
		};
		
		var container = $('#questions-container');
        var questionTemplate = _.template($('#questions-template').html());
        
		$.ajax(params).done(function(data){
			container.html(questionTemplate({questions:data}));
			inintIcheck();
			checkALL();
			checkedForm();
		}).fail(function(erro){
			error(erro);
		})
	});
	
	$(document).on('submit','.examinationForm',function(){
		var data = $(this).serializeArray();
		
		var params = {
				url: '/admin/enterprise/exams/create/',
				type: 'POST',
				dataType: 'json',
				data:data,
		};
		
		$.ajax(params).done(function(resp){
			if(resp.status=='success') {
				BootstrapDialog.alert({title:'提示',message:resp.msg,callback: function(result) {
                    window.location.href= resp.url;
	            }});
			} else {
				BootstrapDialog.alert({title:'提示',message:resp.msg});
			}
		}).fail(function(erro){
			error(erro);
		});
		return false;
	});
	
	var form = $('#examinationForm');
	
	form.on('change',saveForm);
	
	function checkedForm(){
		$('input:checkbox').on('ifChecked', function(event){
			var question_count = 0;
			form.find('input:checkbox').each(function(k,v){
				if($(this)[0].checked == true && parseInt($(this).val()) > 0 ) {
					question_count += 1;
				}
			});
			form.find('input[name=question_count]').val(question_count);
		});
	}
	
	function saveForm(){
		
		var score_count = 0;
		form.find('input[name=score_count]').val(0);
		
		form.find('input[name^=score_]').each(function(key,value){
			if(parseInt($(this).val()) > 0){
				score_count += parseInt($(this).val());
			}
		});
		
		form.find('input[name=score_count]').val(score_count);
		checkedForm();
	}
	
	function saveAutoForm(){
		var radio_num = isNone('radio_num');
		var radio_score = isNone('radio_score');
		var mulit_num = isNone('mulit_num');
		var mulit_score = isNone('mulit_score');
		var judge_num = isNone('judge_num');
		var judge_score = isNone('judge_score');
		var discuss_num = isNone('discuss_num');
		var discuss_score = isNone('discuss_score');
		
		$('.count_ques').text(radio_num+mulit_num+judge_num+discuss_num);
		$('.count_score').text(
				(radio_score*radio_num)+(mulit_score*mulit_num)+(judge_score*judge_num)+(discuss_score*discuss_num)
				);
	}
})